#!/usr/bin/php -q
<?php
	ini_set('memory_limit', '300M');	
#print '<pre>';

	// read from stdin
	$fd = fopen("php://stdin", "r");
	$email = "";
	while (!feof($fd)) {
		$email .= fread($fd, 1024);
	}
	fclose($fd);

	include_once('/var/www/html/tools/spreadsheet-processor/config.php'); 
//	include_once('../config.php');
	require_once('classes/mimeparser/rfc822_addresses.php');
	require_once('classes/mimeparser/mime_parser.php');
	$mime = new mime_parser_class;
	
	/*
	 * Set to 0 for parsing a single message file
	 * Set to 1 for parsing multiple messages in a single file in the mbox format
	 */
	$mime->mbox = 0;
	
	/*
	 * Set to 0 for not decoding the message bodies
	 */
	$mime->decode_bodies = 1;

	/*
	 * Set to 0 to make syntax errors make the decoding fail
	 */
	$mime->ignore_syntax_errors = 1;

	/*
	 * Set to 0 to avoid keeping track of the lines of the message data
	 */
	$mime->track_lines = 1;

	$conversionID = uniqid();
	if(!file_exists($pickUpPath)) {
		@mkdir($pickUpPath, 0775);
	}

	@mkdir($pickUpPath . $conversionID);
	$uploaddir = $pickUpPath . $conversionID . "/";

	$parameters = array(
//		'File'=> "test3.txt"
			'Data' => $email
		/* Save the message body parts to a directory     */
		,	'SaveBody'=> $uploaddir
		/* Do not retrieve or save message body parts     */
		,	'SkipBody'=>1
	);

	$flag = $mime->Decode($parameters, $decoded);
	if (is_array($decoded[0]["Parts"]) == false) {
		@rmdir($uploaddir);
		exit();
	}
	$email_from = $decoded[0]["ExtractedAddresses"]["from:"][0]["address"];		
	foreach($decoded[0]["Parts"] as $part) {
		$mime->Analyze($part, $result);
		$attachments[] = $result;
	}
#	print_r($attachments);	

	if (is_array( $attachments ) ) {
	foreach( $attachments as $attachment ) {
		switch( $attachment["Type"] ) {
			case "ms-excel":
				$i++;
				rename(stripslashes($attachment["DataFile"]), stripslashes($attachment["DataFile"]) . ".xls");
				$attachment["DataFile"] = stripslashes($attachment["DataFile"]) . ".xls";
				$res = processFile( stripslashes($attachment["DataFile"]), $conversionID . "-" . $i );
				unlink($attachment["DataFile"]);

				if ($res["success"]) {
					$list[] = $res;
				} else {
					$errors[] = $res;
				}

				break;
			case "ms-excelx":
				$i++;
				rename(stripslashes($attachment["DataFile"]), stripslashes($attachment["DataFile"]) . ".xlsx");
				$attachment["DataFile"] = stripslashes($attachment["DataFile"]) . ".xlsx";
				$res = processFile( stripslashes($attachment["DataFile"]), $conversionID . "-" . $i );
				unlink($attachment["DataFile"]);

				if ($res["success"]) {
					$list[] = $res;
				} else {
					$errors[] = $res;
				}

				break;
			default:
				unlink($attachment["DataFile"]);
				break;
		}

	}
	}

	if (is_array($list)) {
		$subject = "GBIF: Template Processed";
		$message = "Your archive(s) have been processed. To download click the link(s) below:\r\n";
		foreach($list as $item) {

			$message .= "File: " . $item['pickupFile'] . "\r\n"; 
			if($item['warnings'] != '') $message .= "Warnings: " . $item['warnings'] . "\r\n";
		}
	}
	
	if (is_array($errors)) {
		foreach($errors as $item) {
			$message .= "Error: \r\n";
		}
	}

	mail($email_from, $subject, $message );

	function processFile( $uploadfile, $conversionID ) {
		global $basePath, $baseUri;
		include_once($basePath . "api/classes/gbif.general.php");
		include_once($basePath . "api/classes/gbif.eml.php");
		include_once($basePath . 'api/classes/gbif.processor.php');
		$general = new General($uploadfile);
		$sheetType = $general->getVersion();
		unset($general);

		$path_parts = pathinfo($uploadfile);
		$pickupFile = process($sheetType, $path_parts['basename'], $path_parts['dirname'] . "/", $conversionID );
		$warnings = $pickupFile['warnings'];
		$pickupFile = $pickupFile['pickupFile'];
		$pickupFile = str_ireplace($basePath, $baseUri, $pickupFile);
		$pickupFile = str_replace("//", "/", $pickupFile);
		
		switch($sheetType) {
			default:
				$filename = "dwcarchive.zip";
				break;
			case 'Metadata-1_v1':
				$filename = "eml.xml";
				break;	
		}

		return( array("success" => true, "pickupFile"=> $pickupFile, "filename"=> $filename, "warnings" => $warnings) );
	}
?>